/* 
 * File:   Utils.cpp
 * Author: sgk
 * 
 * Created on March 22, 2010, 12:41 AM
 */

#include "Utils.h"
#include <iostream>
#include <stdlib.h>
#include <arpa/inet.h>

using namespace std;

Utils::Utils() {
}

Utils::Utils(const Utils& orig) {
}

Utils::~Utils() {
}

float Utils::htonf(float value) {

	union v {
		float f;
		unsigned int i;
	};

	union v val;

	val.f = value;
	val.i = htonl(val.i);

	return val.f;
}

void Utils::floatToBytes(float value, char* buffer) {

	value = Utils::htonf(value);

	memcpy(buffer, &value, sizeof (value));

}

void Utils::intToBytes(int value, char* buffer) {

	value = htonl(value);
	memcpy(buffer, &value, sizeof (value));


}

void Utils::fixedStringToBytes(string value, char* buffer) {

	const char* temp = value.c_str();

	for (int i = 0; i < 4; i++) {
		buffer[i] = temp[i];
	}

}

void Utils::StringToBytes(string value, char* buffer) {

	int name_length = Utils::calcStringLength(value.length());
	for (int i = 0; i < name_length+4; i++) {
		buffer[i] = 0;
	}

	const char* temp = value.c_str();

	char stringlen[4] = {0};

	Utils::intToBytes(value.length(), stringlen);
	memmove(buffer, stringlen, 4);

	for (int i = 0; i < value.length(); i++) {
		buffer[i + 4] = temp[i];
	}
	
}

int Utils::calcStringLength(int length) {
	if (length % 4 != 0) {
		length = length + (4 - length % 4);
	}
	return length;
}

bool Utils::isDroppedPacket(double packetLossRate) {

	bool isPacketLost = false;

	double random = drand48();
	cout << "[NETWORK] Packet loss % = " << packetLossRate << " / Random: " << random << endl;
	if (random < 1 - packetLossRate) {
		isPacketLost = false;
	} else {
		isPacketLost = true;
	}

	return isPacketLost;

}
